﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CallBackManager.cs" company="Marcelo Roca">
//   Copyright (c) 2011 Marcelo Roca. All rights reserved.
// </copyright>
// <author name="Marcelo Roca" email="marce@marceloroca.com"/>
// <license>
//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or
//   (at your option) any later version.
// 
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program.  If not, see http://www.gnu.org/licenses/.
// </license>
// --------------------------------------------------------------------------------------------------------------------

namespace GameKits.Unity.HTML5
{
    using System.Collections.Generic;

    using GameKits.LitJson;

    using UnityEngine;

    public delegate void CallBackDelegate(JsonData json);

    internal class CallBackManager : MonoBehaviour
    {
        /// <summary>
        /// La lista de callbacks
        /// </summary>
        private static readonly SortedList<int, CallBackDelegate> callBackList = new SortedList<int, CallBackDelegate>();

        /// <summary>
        /// The current callBackManager
        /// </summary>
        private static CallBackManager current;

        /// <summary>
        /// El contador de callBacks
        /// </summary>
        private static int callBackCounter;

        /// <summary>
        /// Gets Current.
        /// </summary>
        public static CallBackManager Current
        {
            get
            {
                if (current == null)
                {
                    var gO = GameObject.Find("GameKits_Unity_HTML5_CallBackManager");

                    if (gO == null)
                    {
                        gO = new GameObject("GameKits_Unity_HTML5_CallBackManager", typeof(CallBackManager));
                    }

                    current = gO.GetComponent<CallBackManager>();
                    current.Initialize();
                }

                return current;
            }
        }

        /// <summary>
        /// Gets a value indicating whether Initialized.
        /// </summary>
        public bool Initialized { get; private set; }

        /// <summary>
        /// Gets a value indicating whether IsLocalStorage.
        /// </summary>
        public bool IsLocalStorage { get; private set; }

        /// <summary>
        /// Gets a value indicating whether IsSessionStorage.
        /// </summary>
        public bool IsSessionStorage { get; private set; }

        /// <summary>
        /// Gets a value indicating whether ISIndexedDB.
        /// </summary>
        public bool IsIndexedDB { get; private set; }

        /// <summary>
        /// Recive información desde el browser
        /// </summary>
        /// <param name="json">
        /// The json dta.
        /// </param>
        public void ReceiveExternal(string json)
        {
            var jsonData = JsonMapper.ToObject(json);

            int id;

            if (int.TryParse(jsonData["id"].ToString(), out id))
            {
                if (callBackList.ContainsKey(id))
                {
                    try
                    {
                        callBackList[id](jsonData["data"]);
                    }
                    catch
                    {
                    }

                    callBackList.Remove(id);
                }
            }
        }

        /// <summary>
        /// Ejecutamos un procedimiento el el explorador, sin recibir respuesta
        /// </summary>
        /// <param name="varName">
        /// The var name.
        /// </param>
        /// <param name="javaScript">
        /// The java script.
        /// </param>
        public void SendExternal(string varName, string javaScript)
        {
            Application.ExternalEval(
                javaScript + "var GKUHTML5OBJ={ id:-1, data:" + varName + "}; var GKUHTML5JSON=JSON.stringify(GKUHTML5OBJ);" +
                "GetUnity().SendMessage('GameKits_Unity_HTML5_CallBackManager', 'ReceiveExternal', GKUHTML5JSON);");
        }

        /// <summary>
        /// Ejecutamos un procedimiento en el explorador, y nos responden en un callback
        /// </summary>
        /// <param name="varName">
        /// The var name.
        /// </param>
        /// <param name="javaScript">
        /// The java script.
        /// </param>
        /// <param name="callBack">
        /// The call back.
        /// </param>
        public void SendExternal(string varName, string javaScript, CallBackDelegate callBack)
        {
            callBackList.Add(callBackCounter, callBack);

            Application.ExternalEval(
                javaScript + "var GKUHTML5OBJ={ id:" + callBackCounter + ", data:" + varName + "}; var GKUHTML5JSON=JSON.stringify(GKUHTML5OBJ);" +
                "GetUnity().SendMessage('GameKits_Unity_HTML5_CallBackManager', 'ReceiveExternal', GKUHTML5JSON);");

            callBackCounter++;
        }

        /// <summary>
        /// Está función recibe la información de la inicialización
        /// </summary>
        /// <param name="json">
        /// Los datos en formato JsonData
        /// </param>
        private void InitializeCallBack(JsonData json)
        {
            this.IsLocalStorage = (bool)json["localstorage"];
            this.IsSessionStorage = (bool)json["sessionstorage"];
            this.IsIndexedDB = (bool)json["indexeddb"];

            this.Initialized = true;

            GuiForms.Forms.LoggerForm.LogMessage(
                "ReceiveModernizerValues: ls=" + this.IsLocalStorage + 
                " ss=" + this.IsSessionStorage + 
                " idb=" + this.IsIndexedDB);
        }

        /// <summary>
        /// Inicializamos el manager
        /// </summary>
        private void Initialize()
        {
            if (Application.isWebPlayer)
            {
                callBackCounter = 0;

                this.SendExternal(
                    "mdrnzrValues",
                    "var mdrnzrValues={localstorage:Modernizr.localstorage, sessionstorage:Modernizr.sessionstorage, indexeddb:Modernizr.indexeddb};",
                    this.InitializeCallBack);
            }
        }
    }
}
